﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Threading;
using System.Globalization;
using System.Reflection;
using SilverPOP.Library.BusinessEntities;
using SilverPOP.Library.Utilities;
using SilverPOP.Library.com.silverpop.api5;
using Newtonsoft.Json;
using System.Configuration;

namespace SilverPOP.Library.Helpers
{
    public class SilverPopHelpers
    {
        #region Silver Pop Account Login
        private static EngageSoapApiClientService LoginToSilverPopAccount(string userName, string password)
        {

            EngageSoapApiClientService client = new EngageSoapApiClientService();

            LoginRequestType loginType = new LoginRequestType();
            loginType.USERNAME = userName;
            loginType.PASSWORD = password;


            SessionMgmtResponseType session = client.Login(loginType);

            if (session.SUCCESS)
            {
                client.sessionHeader = new sessionheadertype { sessionid = session.SESSIONID }; //Assign new session header with valid SessionID
                return client;
            }
            
            throw new Exception(session.Fault.FaultString);
        }
        #endregion

        #region Send Mail

        #region Send Mail By Calling Web Service

        public static String SendMail(SilverPopAccount silverPopAccount,String recipientMail,long mailingID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            SendMailingRequestType mailingRequest = new  SendMailingRequestType();
            mailingRequest.MailingId = mailingID;
            mailingRequest.RecipientEmail = recipientMail;
            
            SendMailingResponseType mailResponse = client.SendMailing(mailingRequest);

            if (mailResponse.SUCCESS)
            {
                return SilverPOPMessages.MAIL_SEND_SUCCESSFULL;
            }
            else
            {
                throw new Exception(mailResponse.Fault.FaultString);
            }
        }

        #endregion

        #region Send Mail By Calling Direct XML API
        public static String  SendMailByDirectXMLAPI(SilverPopAccount silverPopAccount,String recipientMail,long mailingID)
        {
            String xmlDocument = "<Envelope>"
                                   + "<Body>"
                                   + "<SendMailing>"
                                   + "<MailingId>"+ mailingID+"</MailingId>"
                                   + "<RecipientEmail>"+ recipientMail+"</RecipientEmail>"
                                   + "</SendMailing>"
                                   + "</Body>"
                                   + "</Envelope>";
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://api5.silverpop.com/XMLAPI");
            myReq.Method = "POST";
            myReq.ContentType = "text/xml";
            myReq.Timeout = 30000;
            myReq.Headers.Add("SOAPAction", ":\"#save\"");

            byte[] PostData = Encoding.UTF8.GetBytes(xmlDocument);
            myReq.ContentLength = PostData.Length;
            String successValue=String.Empty;
            using (Stream requestStream = myReq.GetRequestStream())
            {
                requestStream.Write(PostData, 0, PostData.Length);
            }
            HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
            StreamReader streamReader = new StreamReader(response.GetResponseStream());
            XmlReader reader = XmlReader.Create(streamReader);
            reader.MoveToContent();
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name.ToLower() == "success")
                    {
                         successValue = reader.ReadElementString();
                    }

                    if (!String.IsNullOrEmpty(successValue) && successValue.ToLower() == "true")
                    {
                         return SilverPOPMessages.MAIL_SEND_SUCCESSFULL;
                    }

                    if ( ( !String.IsNullOrEmpty(successValue) && successValue.ToLower() == "false" ) && reader.Name.ToLower() == "faultstring")
                    {
                        string faultMessage = reader.ReadElementString();
                        return faultMessage;
                    }
                }
            }
            return String.Empty;
        }
        #endregion

        #endregion

        #region Add Member To A Contact List

        public static String AddMember(SilverPopAccount silverPopAccount, Object contact, long databaseID)
        {
            //Automatic data job id for adding contact from database to Contact List: 18147037

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            AddRecipientRequestType recipientType = new AddRecipientRequestType();
            recipientType.CREATED_FROM = 1;
            recipientType.LIST_ID = databaseID;         //database id:2260608
            recipientType.UPDATE_IF_FOUND = true;
            recipientType.SEND_AUTOREPLY = true;


            recipientType.COLUMN = AddColumnElements(contact);

            ListMgmtResponseType accountResponse = client.AddRecipient(recipientType);

            if (accountResponse.SUCCESS)
            {

                return SilverPOPMessages.CONTACT_ADDED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }

        }


        private static ColumnElementType[] AddColumnElements(Object contact)
        {
            int counter = 0;
            int columnCount = contact.GetType().GetProperties().Count();
            ColumnElementType[] columnType = new ColumnElementType[columnCount];

            PropertyInfo[] fieldInfo = contact.GetType().GetProperties();

            foreach (PropertyInfo col in fieldInfo)
            {
               columnType[counter] = new ColumnElementType();
               columnType[counter].NAME = col.Name;
               columnType[counter].VALUE = col.GetValue(contact, null) != null ? col.GetValue(contact, null).ToString() : String.Empty;
               counter++;
            }

            return columnType;

        }

        //private static int GetDynamicColumnData(List<DynamicData> dynamicDataList,  ColumnElementType[] columnType, int counter)
        //{
        //    foreach (DynamicData dataItem in dynamicDataList)
        //    {
        //        if (!String.IsNullOrEmpty(dataItem.Name.Trim()))
        //        {
        //            columnType[counter] = new ColumnElementType();
        //            columnType[counter].NAME = dataItem.Name.Trim();
        //            columnType[counter].VALUE = !String.IsNullOrEmpty(dataItem.Value.Trim()) ? dataItem.Value.Trim() : String.Empty;
        //            counter++;
        //        }
        //    }

        //    return counter;
        //}


        public static String AddMember(SilverPopAccount silverPopAccount, String addingNewMemberEmail,long databaseID)
        {
            //Automatic data job id for adding contact from database to Contact List: 18147037

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            AddRecipientRequestType recipientType = new  AddRecipientRequestType();
            recipientType.CREATED_FROM = 1;
            recipientType.LIST_ID = databaseID;         //database id:2260608
            recipientType.UPDATE_IF_FOUND = true;
            recipientType.SEND_AUTOREPLY = true;

            ColumnElementType[] columnType = new  ColumnElementType[2];
            columnType[0] = new  ColumnElementType();
            columnType[0].NAME = "EMAIL";
            columnType[0].VALUE = addingNewMemberEmail;

            recipientType.COLUMN = columnType;

            ListMgmtResponseType accountResponse = client.AddRecipient(recipientType);

            if (accountResponse.SUCCESS)
            {
              
                return SilverPOPMessages.CONTACT_ADDED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }

        }


        public static String AddMember(SilverPopAccount silverPopAccount, String addingNewMemberEmail, String firstName, long databaseID)
        {
            //Automatic data job id for adding contact from database to Contact List: 18147037

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            AddRecipientRequestType recipientType = new AddRecipientRequestType();
            recipientType.CREATED_FROM = 1;
            recipientType.LIST_ID = databaseID;         //database id:2260608
            recipientType.UPDATE_IF_FOUND = true;

            ColumnElementType[] columnType = new ColumnElementType[2];
            columnType[0] = new ColumnElementType();
            columnType[0].NAME = "EMAIL";
            columnType[0].VALUE = addingNewMemberEmail;
            columnType[1] = new ColumnElementType();
            columnType[1].NAME = "FirstName";
            columnType[1].VALUE = firstName;

            recipientType.COLUMN = columnType;

            ListMgmtResponseType accountResponse = client.AddRecipient(recipientType);

            if (accountResponse.SUCCESS)
            {
                return SilverPOPMessages.CONTACT_ADDED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }

        }

        public static string AddMultipleMember(SilverPopAccount silverPopAccount, long databaseID, List<String> addingMemberDetail, List<String> databaseField)
        {
            //Automatic data job id for adding contact from database to Contact List: 18147037

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);
            string msg = "Total Contact: " + addingMemberDetail.Count() + "\n";
            int countSuccess = 0;

            foreach (string detail in addingMemberDetail)
            {
                string[] contactDetail = detail.Split(',');
                if (contactDetail.Count() > 0)
                {
                    AddRecipientRequestType recipientType = new AddRecipientRequestType();
                    recipientType.CREATED_FROM = 1;
                    recipientType.LIST_ID = databaseID;
                    recipientType.UPDATE_IF_FOUND = true;

                    ColumnElementType[] columnType = new ColumnElementType[databaseField.Count()];
                    int i = 0;
                    foreach (string field in databaseField)
                    {
                        columnType[i] = new ColumnElementType();
                        columnType[i].NAME = field;
                        columnType[i].VALUE = contactDetail[i];
                        i++;
                    }
                    recipientType.COLUMN = columnType;

                    ListMgmtResponseType accountResponse = client.AddRecipient(recipientType);

                    if (accountResponse.SUCCESS)
                    {
                        countSuccess++;
                    }
                    else
                    {
                        msg += accountResponse.Fault.FaultString + "\n";
                    }
                }
            }

            return msg += "Total Success: " + countSuccess ;
        }

        public static String AddMemberToContactList(SilverPopAccount silverPopAccount, String addingNewMemberEmail, String firstName, long contactListId)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            AddContactToContactListRequestType recipientType = new AddContactToContactListRequestType();

            recipientType.CONTACT_ID = contactListId;

            ColumnNameValueElementType[] columnType = new ColumnNameValueElementType[2];
            columnType[0] = new ColumnNameValueElementType();
            columnType[0].NAME = "EMAIL";
            columnType[0].VALUE = addingNewMemberEmail;
            columnType[1] = new ColumnNameValueElementType();
            columnType[1].NAME = "FirstName";
            columnType[1].VALUE = firstName;

            recipientType.COLUMN = columnType;

            ListMgmtUserActionsResponseType accountResponse = client.AddContactToContactList(recipientType);

            if (accountResponse.SUCCESS)
            {
                return SilverPOPMessages.CONTACT_ADDED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }
        }

        public static String AddMemberToSuppressionList(SilverPopAccount silverPopAccount, string recepientMail, long listId)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            AddRecipientRequestType recipientType = new AddRecipientRequestType();
            recipientType.CREATED_FROM = 3;
            recipientType.LIST_ID = listId;
            recipientType.UPDATE_IF_FOUND = true;

            ColumnElementType[] columnType = new ColumnElementType[1];
            columnType[0] = new ColumnElementType();
            columnType[0].NAME = "Email";
            columnType[0].VALUE = recepientMail;

            recipientType.COLUMN = columnType;

            ListMgmtResponseType accountResponse = client.AddRecipient(recipientType);

            if (accountResponse.SUCCESS)
            {
                return SilverPOPMessages.CONTACT_ADDED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }
        }

        #endregion

        #region Remove A Member From A Contact

        public static String RemoveMember(SilverPopAccount silverPopAccount, String removeMemberEmail,long databaseID)
        {

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);
            
            RemoveRecipientRequestType recipientType = new  RemoveRecipientRequestType();
            recipientType.LIST_ID = databaseID;         //database id:2260608
            recipientType.EMAIL = removeMemberEmail;

             ListMgmtUserActionsResponseType accountResponse = client.RemoveRecipient(recipientType);

            if (accountResponse.SUCCESS)
            {
                return SilverPOPMessages.CONTACT_REMOVED_SUCCESSFULL;
            }
            else
            {
                throw new Exception(accountResponse.Fault.FaultString);
            }

        }


        #endregion

        #region Get Mailing Template List
        public static List<String> GetMailingTemplatesList(SilverPopAccount silverPopAccount)
        {
            //Test Mailing Templates: MailingID: 6273484  Template Name: Rabbi Testing

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

             GetMailingTemplatesRequestType templateType = new  GetMailingTemplatesRequestType();
            //templateType.VISIBILITY=0 ; //private
            templateType.VISIBILITY = 1; //shared

             MailMgmtUserActionsResponseType templateListResponse = client.GetMailingTemplates(templateType);

            if (templateListResponse.SUCCESS && templateListResponse.MAILING_TEMPLATE.Count() > 0)
            {
                List<String> templateList = new List<String>();
                
                foreach ( MailingTemplateElementType templateElement in templateListResponse.MAILING_TEMPLATE)
                {
                    templateList.Add(templateElement.MAILING_ID.ToString() + " " + templateElement.MAILING_NAME);
                }

                return templateList;

            }
            else
            {
                throw new Exception(templateListResponse.Fault.FaultString);
            }
        }
        #endregion

        #region Get Database Related Information  
        public static List<String> GetDatabaseList(SilverPopAccount silverPopAccount)
        {
            //Test Database: Database Id: 2258790  Name: Rabbi Test ContactList Count: 1

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

             GetListsRequestType databaseList = new  GetListsRequestType();
            //databaseList.VISIBILITY = 0;  //private
            databaseList.VISIBILITY = 1;  //shared

             ListMgmtUserActionsResponseType databaseListResponse = client.GetLists(databaseList);

            if (databaseListResponse.SUCCESS && databaseListResponse.LIST.Count() > 0)
            {
                List<String> dtbaseList = new List<String>();

                foreach ( ListElementType listElement in databaseListResponse.LIST)
                {
                    dtbaseList.Add(listElement.ID.ToString() + " " + listElement.NAME + " " + listElement.SIZE);
                }
                return dtbaseList;
            }
            else
            {
                throw new Exception(databaseListResponse.Fault.FaultString);
            }

        }

        public static DatabaseInfo GetDBorListMetadata(SilverPopAccount silverPopAccount, long databaseID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
            {
                DatabaseInfo dbInfo = new DatabaseInfo(-111, SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);
                return dbInfo;
            }

            GetListMetaDataRequestType _DBorListMetadata = new GetListMetaDataRequestType();

            _DBorListMetadata.LIST_ID = databaseID;

            ListMgmtUserActionsResponseType metadataResponse = client.GetListMetaData(_DBorListMetadata);

           

            if (metadataResponse.SUCCESS)
            {
                DatabaseInfo dbInfo=new DatabaseInfo(metadataResponse.ID,metadataResponse.NAME,metadataResponse.SIZE,metadataResponse.NUM_OPT_OUTS,metadataResponse.NUM_UNDELIVERABLE);
                return dbInfo;
            }
            else
            {
                DatabaseInfo dbInfo = new DatabaseInfo(-111,metadataResponse.Fault.FaultString);
                return dbInfo;
            }
        }

        public static void GetListReciepientMailings(SilverPopAccount silverPopAccount, long databaseID, long mailingID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            ListRecipientMailingsRequestType _request = new ListRecipientMailingsRequestType();
            _request.LIST_ID = databaseID;
            _request.RECIPIENT_ID = mailingID;


            ListMgmtUserActionsResponseType databaseListResponse = client.ListRecipientMailings(_request);

            if (databaseListResponse.SUCCESS)
            {
            
            }
            else
            {

            }
        }

        #endregion

        #region Preview Mailing Template Before Send
        public static String PreviewMailingTemplateBeforeSend(SilverPopAccount silverPopAccount, long mailingID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            PreviewMailingRequestType mailTemplatePreview = new  PreviewMailingRequestType();
            mailTemplatePreview.MailingId = mailingID;

            MailMgmtUserActionsResponseType templateViewResponse = client.PreviewMailing(mailTemplatePreview);

            if (templateViewResponse.SUCCESS)
            {
                return templateViewResponse.HTMLBody;
            }
            else
            {
                throw new Exception(templateViewResponse.Fault.FaultString);
            }
        }
        #endregion

        #region Export Raw Report Data From SilverPOP

        public static String RawRecipientDataExport(SilverPopAccount silverPopAccount, long mailingID, String fileName, DateTime eventStartDate, DateTime eventEndDate)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            DateTime sDate;
            DateTime eDate;

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            RawRecipientDataExportRequestType reqType = new RawRecipientDataExportRequestType();
            reqType.EMAIL = silverPopAccount.LoginEmail;

            if (eventStartDate == default(DateTime))
            {
                sDate = new DateTime(2013, 8, 1);
            }
            else
            {
                sDate = eventStartDate;
            }

            if (eventEndDate == default(DateTime))
            {
                eDate = DateTime.Now;
            }
            else
            {
                eDate = eventEndDate;
            }

            reqType.MAILING_ID = mailingID;
            reqType.MAILING_IDSpecified = true;
            //reqType.MOVE_TO_FTP = "sftp://shahriar@desme.com:desmEPa$$@transfer5.silverpop.com";
            reqType.MOVE_TO_FTP = "true"; //"transfer5.silverpop.com";
            reqType.EXPORT_FILE_NAME = fileName;
            reqType.EXPORT_FORMAT = 0; //0 refer to csv format
            reqType.EVENT_DATE_START = string.Format("{0:MM/dd/yyyy hh:mm:ss}", sDate);
            reqType.EVENT_DATE_END = string.Format("{0:MM/dd/yyyy hh:mm:ss}", eDate);

            //reqType.ALL_EVENT_TYPES = "true";
            //reqType.SENT = "true";
            reqType.OPENS = "true";
            reqType.CLICKS = "true";
            reqType.HARD_BOUNCES = "true";
            reqType.SOFT_BOUNCES = "true";
            //reqType.EXCLUDE_DELETED = "true";

            try
            {
                reqType.ALL_NON_EXPORTED = ConfigurationManager.AppSettings["INCREMENTAL_FETCH"].ToString().ToLower();  //"true";
            }
            catch (Exception ex)
            {
                reqType.ALL_NON_EXPORTED = "true";
            }


            //additional column which we want in our report csv file
            reqType.COLUMNS = new ColumnElementType1[1];
            reqType.COLUMNS[0] = new ColumnElementType1();
            reqType.COLUMNS[0].NAME = "ProspectId";

            ReportingResponseType _response = client.RawRecipientDataExport(reqType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.MAILING.FILE_PATH + ":" + _response.MAILING.JOB_ID + ":" + _response.JOB_STATUS;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }



        public static String RawRecipientSentDataExport(SilverPopAccount silverPopAccount, long mailingID, String fileName, DateTime eventStartDate, DateTime eventEndDate)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            DateTime sDate;
            DateTime eDate;

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            RawRecipientDataExportRequestType reqType = new RawRecipientDataExportRequestType();
            reqType.EMAIL = silverPopAccount.LoginEmail;

            if (eventStartDate == default(DateTime))
            {
                sDate = new DateTime(2013, 8, 1);
            }
            else
            {
                sDate = eventStartDate;
            }

            if (eventEndDate == default(DateTime))
            {
                eDate = DateTime.Now;
            }
            else
            {
                eDate = eventEndDate;
            }

            reqType.MAILING_ID = mailingID;
            reqType.MAILING_IDSpecified = true;
            //reqType.MOVE_TO_FTP = "sftp://shahriar@desme.com:desmEPa$$@transfer5.silverpop.com";
            reqType.MOVE_TO_FTP = "true"; //"transfer5.silverpop.com";
            reqType.EXPORT_FILE_NAME = fileName;
            reqType.EXPORT_FORMAT = 0; //0 refer to csv format
            reqType.EVENT_DATE_START = string.Format("{0:MM/dd/yyyy hh:mm:ss}", sDate);
            reqType.EVENT_DATE_END = string.Format("{0:MM/dd/yyyy hh:mm:ss}", eDate);

            //reqType.ALL_EVENT_TYPES = "true";
            reqType.SENT = "true";

            //additional column which we want in our report csv file
            reqType.COLUMNS = new ColumnElementType1[1];
            reqType.COLUMNS[0] = new ColumnElementType1();
            reqType.COLUMNS[0].NAME = "ProspectId";

            ReportingResponseType _response = client.RawRecipientDataExport(reqType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.MAILING.FILE_PATH + ":" + _response.MAILING.JOB_ID + ":" + _response.JOB_STATUS;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }


        public static String RawRecipientDataExport(SilverPopAccount silverPopAccount, long mailingID, String fileName)
        {
            /*
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            RawRecipientDataExportRequestType reqType = new RawRecipientDataExportRequestType();
            reqType.EMAIL = silverPopAccount.LoginEmail;
            
            reqType.MAILING_ID = mailingID;
            reqType.MAILING_IDSpecified = true;
            //reqType.MOVE_TO_FTP = "sftp://shahriar@desme.com:desmEPa$$@transfer5.silverpop.com";
            reqType.MOVE_TO_FTP = "true"; //"transfer5.silverpop.com";
            reqType.EXPORT_FILE_NAME = fileName;
            reqType.EXPORT_FORMAT = 0; //0 refer to csv format

            reqType.ALL_EVENT_TYPES = "false";
            reqType.SENT = "true";
            reqType.OPENS = "true";
            reqType.CLICKS = "true";
            reqType.HARD_BOUNCES = "true";
            reqType.SOFT_BOUNCES = "true";
            reqType.OPTOUTS = "true";

            
            reqType.CLICKSTREAMS = "false";
            reqType.CONVERSIONS = "false";
            reqType.ATTACHMENTS = "false";
            reqType.FORWARDS = "false";
            reqType.OPTINS = "false";
            reqType.REPLY_ABUSE = "false";
            reqType.REPLY_COA = "false";
            reqType.MAIL_BLOCKS = "false";
            reqType.MAILING_RESTRICTIONS = "false";
            reqType.REPLY_OTHER = "false";
            reqType.SUPPRESSED = "false";
            reqType.SMS_ERROR = "false";
            reqType.SMS_REJECT = "false";
            reqType.SMS_OPTOUT = "false";
            
            

            reqType.ALL_NON_EXPORTED = "true";
            
            //additional column which we want in our report csv file
            reqType.COLUMNS = new ColumnElementType1[1];
            reqType.COLUMNS[0] = new ColumnElementType1();
            reqType.COLUMNS[0].NAME = "ProspectId";

            ReportingResponseType _response = client.RawRecipientDataExport(reqType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.MAILING.FILE_PATH + ":" + _response.MAILING.JOB_ID + ":" + _response.JOB_STATUS;
            }
            else
            {
                return _response.Fault.FaultString;
            }
             */
            return String.Empty;
        }

       
        public static String RawRecipientDataExportByDatabaseId(SilverPopAccount silverPopAccount, long listID, String fileName)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            RawRecipientDataExportRequestType reqType = new RawRecipientDataExportRequestType();
            reqType.EMAIL = silverPopAccount.LoginEmail;

            //reqType.MAILING_ID = 2142172;
            //reqType.MAILING_ID = 6422844;
            reqType.LIST_ID = listID;
            reqType.LIST_IDSpecified = true;
            //reqType.MOVE_TO_FTP = "sftp://shahriar@desme.com:desmEPa$$@transfer5.silverpop.com";
            reqType.MOVE_TO_FTP = "transfer5.silverpop.com";
            reqType.EXPORT_FILE_NAME = fileName;
            reqType.EXPORT_FORMAT = 0; //0 refer to csv format

            reqType.COLUMNS = new ColumnElementType1[1];
            reqType.COLUMNS[0] = new ColumnElementType1();
            reqType.COLUMNS[0].NAME = "ProspectId";

            ReportingResponseType _response = client.RawRecipientDataExport(reqType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.MAILING.FILE_PATH + ":" + _response.MAILING.JOB_ID + ":" + _response.JOB_STATUS;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }


        public static String RawRecipientDataExportForSuppresion(SilverPopAccount silverPopAccount, long mailingID, String fileName)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            RawRecipientDataExportRequestType reqType = new RawRecipientDataExportRequestType();
            reqType.EMAIL = silverPopAccount.LoginEmail;

            //reqType.MAILING_ID = 2142172;
            //reqType.MAILING_ID = 6422844;
            reqType.MAILING_ID = mailingID;
            reqType.MAILING_IDSpecified = true;
            //reqType.MOVE_TO_FTP = "sftp://shahriar@desme.com:desmEPa$$@transfer5.silverpop.com";
            reqType.MOVE_TO_FTP = "transfer5.silverpop.com";
            reqType.EXPORT_FILE_NAME = fileName;
            reqType.EXPORT_FORMAT = 0; //0 refer to csv format
            reqType.SUPPRESSED = "Suppressed";
            reqType.OPTOUTS = "Opt Out";

            reqType.COLUMNS = new ColumnElementType1[1];
            reqType.COLUMNS[0] = new ColumnElementType1();
            reqType.COLUMNS[0].NAME = "ProspectId";

            ReportingResponseType _response = client.RawRecipientDataExport(reqType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.MAILING.FILE_PATH;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }

        public static String ExportList(SilverPopAccount silverPopAccount, long listID,DateTime eventStartDate=default(DateTime), DateTime eventEndDate=default(DateTime))
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            DateTime sDate;
            DateTime eDate;

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;

            ExportListRequestType _request = new ExportListRequestType();


            if (eventStartDate == default(DateTime))
            {
                sDate = new DateTime(2013, 8, 1);
            }
            else
            {
                sDate = eventStartDate;
            }

            if (eventEndDate == default(DateTime))
            {
                eDate = DateTime.Now;
            }
            else
            {
                eDate = eventEndDate;
            }

            _request.LIST_ID = listID;
            _request.EXPORT_TYPE = ExportType.OPT_OUT;
            _request.EXPORT_FORMAT = ListTableExportFormat.CSV;
            _request.DATE_START = string.Format("{0:MM/dd/yyyy hh:mm:ss}", sDate);
            _request.DATE_END = string.Format("{0:MM/dd/yyyy hh:mm:ss}", eDate);

            ListMgmtUserActionsResponseType _response = client.ExportList(_request);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.FILE_PATH + ":" + _response.JOB_ID + ":" + "WAITING";
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }

       

        public static List<SummaryReport> GetAggregateTrackingForMailing(SilverPopAccount silverPopAccount, List<SilverPOPReportIDInfo> silverPOPReportInfoList)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception(SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            List<SummaryReport> summaryReportList = new List<SummaryReport>();

            foreach (SilverPOPReportIDInfo silverpopReportInfo in silverPOPReportInfoList)
            {
                GetAggregateTrackingForMailingRequestType _request = new GetAggregateTrackingForMailingRequestType();
                _request.MAILING_ID = silverpopReportInfo.MailingId;
                _request.REPORT_ID = silverpopReportInfo.ReportId;
                _request.TOP_DOMAIN = "true";
                //_request.PER_CLICK = "true";

                ReportingResponseType _response = client.GetAggregateTrackingForMailing(_request);

                if (_response.SUCCESS)
                {
                    //MailingElementType mailing = _response.Mailing[0];
                    //TopDomainElementType topDomain = _response.TopDomains[0];
                    
                    int sentCount,bouncedCount,openCount,clickCount,optOutCount;
                    sentCount = bouncedCount = openCount = clickCount = optOutCount = 0;

                    foreach (MailingElementType elementType in _response.Mailing)
                    {
                        bouncedCount += elementType.NumBounceHard + elementType.NumBounceSoft;
                        sentCount += elementType.NumSent;
                        openCount += elementType.NumGrossOpen;
                        clickCount += elementType.NumGrossClick;
                    }

                    foreach (TopDomainElementType domainElementType in _response.TopDomains)
                    {
                        optOutCount += domainElementType.Unsubscribe;
                    }


                    
                    //int totalBounced = mailing.NumBounceHard + mailing.NumBounceSoft;
                    
                    SummaryReport summaryReport = new SummaryReport(silverpopReportInfo.BlastId, silverpopReportInfo.SegmentId,silverpopReportInfo.MailingId,
                                                                     sentCount, bouncedCount, openCount, clickCount, optOutCount);
                    summaryReportList.Add(summaryReport);
                }
                else
                {
                    summaryReportList.Add(new SummaryReport(_response.Fault.FaultString));
                }
            }

            return (summaryReportList != null && summaryReportList.Count > 0) ? summaryReportList : null;
        }

        public static List<SummaryReport> GetUniqueTrackingForMailing(SilverPopAccount silverPopAccount, List<SilverPOPReportUniqueCount> silverPOPReportUniqueReport)
        {
           
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception(SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            List<SummaryReport> summaryReportList = new List<SummaryReport>();

            foreach (SilverPOPReportUniqueCount uniqueReport in silverPOPReportUniqueReport)
            {
                GetAggregateTrackingForMailingRequestType _request = new GetAggregateTrackingForMailingRequestType();
                _request.MAILING_ID = uniqueReport.MailingId;
                _request.REPORT_ID = uniqueReport.ReportId;
                _request.TOP_DOMAIN = "true";
                //_request.PER_CLICK = "true";

                ReportingResponseType _response = client.GetAggregateTrackingForMailing(_request);

                if (_response.SUCCESS)
                {

                    //foreach (MailingElementType elementType in _response.Mailing)
                    //{
                    SummaryReport summaryReport = new SummaryReport(uniqueReport.BlastId, uniqueReport.SegmentId, uniqueReport.MailingId,
                                                                        _response.Mailing[0].NumUniqueOpen, _response.Mailing[0].NumUniqueClick);

                        summaryReportList.Add(summaryReport);
                    //}
                }
                else
                {
                    summaryReportList.Add(new SummaryReport(_response.Fault.FaultString));
                }
            }

            return (summaryReportList != null && summaryReportList.Count > 0) ? summaryReportList : null;
        }




        public static CustomReport GetAggregateTrackingForUser(SilverPopAccount silverPopAccount, string mailAddress, DateTime startDate, DateTime endDate)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            GetAggregateTrackingForUserRequestType _request = new GetAggregateTrackingForUserRequestType();

            _request.DATE_START = string.Format("{0:MM/dd/yyyy H:mm:ss}", startDate);
            _request.DATE_END = string.Format("{0:MM/dd/yyyy H:mm:ss}", endDate);
            _request.OPTIONALUSER = mailAddress;

            ReportingResponseType _reportResponse = client.GetAggregateTrackingForUser(_request);
            CustomReport _customReport = new CustomReport();

            if (_reportResponse.SUCCESS)
            {
                _customReport.NumSent += _reportResponse.Mailing[0].NumSent;
                _customReport.NumSeeds += _reportResponse.Mailing[0].NumSeeds;
                _customReport.NumSuppressed += _reportResponse.Mailing[0].NumSuppressed;
                _customReport.NumBounceHard += _reportResponse.Mailing[0].NumBounceHard;
                _customReport.NumBounceSoft += _reportResponse.Mailing[0].NumBounceSoft;
                _customReport.NumUniqueOpen += _reportResponse.Mailing[0].NumUniqueOpen;
                _customReport.NumGrossOpen += _reportResponse.Mailing[0].NumGrossOpen;
                _customReport.NumUniqueClick += _reportResponse.Mailing[0].NumUniqueClick;
                _customReport.NumGrossClick += _reportResponse.Mailing[0].NumGrossClick;

                return _customReport;
            }
            else
            {
                return null;
            } 
        }

        public static String TrackingMatricExport(SilverPopAccount silverPopAccount, long mailingId, long listId)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            TrackingMetricExportRequestType _request = new TrackingMetricExportRequestType();

            _request.MAILING_ID = mailingId;// 6331204;
            _request.LIST_ID = listId;// 2260608;

            ReportingResponseType _response = client.TrackingMetricExport(_request);

            if (_response.SUCCESS)
            {
                return _response.JOB_DESCRIPTION;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }
        #endregion

        #region Schedule Mail

        public static long CreateScheduleMail(SilverPopAccount silverPopAccount, long templateId, long databaseId, long[] suppressionList, string mailingName, string scheduleTime)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            ScheduleMailingRequestType _scheduleMail = new ScheduleMailingRequestType();
            _scheduleMail.TEMPLATE_ID = templateId;
            _scheduleMail.LIST_ID = databaseId;
            _scheduleMail.SCHEDULED = scheduleTime;
            _scheduleMail.SUPPRESSION_LISTS = suppressionList;
            _scheduleMail.MAILING_NAME = mailingName;
            _scheduleMail.VISIBILITY = 1;
            _scheduleMail.INBOX_MONITOR = "true";
            _scheduleMail.SEND_HTML = "true";

            MailMgmtUserActionsResponseType _response = client.ScheduleMailing(_scheduleMail);

            if (_response.SUCCESS)
            {
                return _response.MAILING_ID;
            }
            else
            {
                throw new Exception(_response.Fault.FaultString);
            }
        }

        #endregion

        #region Create Table

        //Not Complted XXX
        public static void CreateRelationalTable(SilverPopAccount silverPopAccount)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            CreateTableRequestType _request = new CreateTableRequestType();

            _request.TABLE_NAME = "Test Table";

            TableColumnElementType[] columnType = new TableColumnElementType[3];

            columnType[0] = new TableColumnElementType();
            columnType[0].NAME = "Id";
            columnType[0].TYPE = TableColumnType.NUMERIC;
            columnType[0].KEY_COLUMN = true;

            columnType[1] = new TableColumnElementType();
            columnType[1].NAME = "Name";
            columnType[1].TYPE = TableColumnType.TEXT;

            columnType[2] = new TableColumnElementType();
            columnType[2].NAME = "Email";
            columnType[2].TYPE = TableColumnType.EMAIL;

            _request.COLUMNS = columnType;

            ListMgmtUserActionsResponseType databaseListResponse = client.CreateTable(_request);

            if (databaseListResponse.SUCCESS)
            {

            }
            else
            {

            }
        }

        #endregion

        #region Add Custom Column In An Existing Database

        public static string AddCustomColumnInSilverPOPDB(SilverPopAccount silverPopAccount, long listOrDBId, List<CustomDBColumn> customColumnList)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);
            string message = string.Empty;
            bool errorOccured = false;
            AddListColumnRequestType _request = new AddListColumnRequestType();
            string jobId = String.Empty;
            
            foreach (CustomDBColumn customDBColumn in customColumnList)
            {
                _request.COLUMN_NAME = customDBColumn.ColumnName;
                _request.COLUMN_TYPE = customDBColumn.ColumnDataType;
                _request.LIST_ID = listOrDBId;

                ListMgmtUserActionsResponseType response = client.AddListColumn(_request);


                if (!response.SUCCESS)
                {
                    message += customDBColumn.ColumnName + ", ";
                    errorOccured = true;
                }
                else
                {
                    jobId = response.JOB_ID.ToString();
                }
            }

            if (errorOccured)
            {
                return "Cannot add this fields: " + message;
            }
            else
            {
                return "Successfully added all the fields. Job Id: " + jobId;
            }

        }

        #endregion


        #region Create Contact List

        public static long CreateContactList(SilverPopAccount silverPopAccount,long databaseId,String contactListName,int visibility)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception( SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            CreateContactListRequestType contactListRequest=new CreateContactListRequestType();
            contactListRequest.CONTACT_LIST_NAME=contactListName;
            contactListRequest.DATABASE_ID=databaseId;
            contactListRequest.VISIBILITY=visibility;

           ListMgmtUserActionsResponseType cotactListCreateResponse =  client.CreateContactList(contactListRequest);


           if (cotactListCreateResponse.SUCCESS)
            {
               return cotactListCreateResponse.CONTACT_LIST_ID;
            }
            else
            {
                throw new Exception(cotactListCreateResponse.Fault.FaultString);
            }
        }


        #endregion

        #region Imports  

        public static Dictionary<String,String> ImportDataToSilverPOPDatabase(SilverPopAccount silverPopAccount, List<String> fileNameListCSVWithXmlMapper)
        {

            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);
            Dictionary<String, String> importResult = new Dictionary<string, string>();

            if (client == null)
            {
                importResult.Add("Error", SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);
                return importResult;
            }

            foreach (String fileName in fileNameListCSVWithXmlMapper)
            {
                ImportListRequestType importListRequestType=new ImportListRequestType();
                importListRequestType.SOURCE_FILE = fileName;
                importListRequestType.MAP_FILE = fileName.Replace(".csv",".xml");

                ListMgmtUserActionsResponseType importDataResponse = client.ImportList(importListRequestType);

                if (importDataResponse.SUCCESS)
                {
                    importResult.Add(fileName, "Success-" + importDataResponse.JOB_ID);
                }
                else
                {
                    importResult.Add(fileName, importDataResponse.Fault.FaultString);
                }
            }

            return importResult;
        }

        #endregion

        #region Opt Out 

        public static string OptOutRecipient(SilverPopAccount silverPopAccount, long listId, string email)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception(SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            OptOutRecipientRequestType _request = new OptOutRecipientRequestType();
            _request.LIST_ID = listId;
            _request.EMAIL = email;

            //ColumnElementType[] columnType = new ColumnElementType[1];

            //columnType[0] = new ColumnElementType();
            //columnType[0].NAME = "ProspectId";
            //columnType[0].VALUE = prospectId.ToString();

            //_request.COLUMN = columnType;

            ListMgmtResponseType _response = client.OptOutRecipient(_request);

            if (_response.SUCCESS)
            {
                return SilverPOPMessages.OPT_OUT_SUCCESSFULL;
            }
            else
            {
                throw new Exception(_response.Fault.FaultString);
            }
        }

        public static string OptInAgain(SilverPopAccount silverPopAccount, long listId, string email, string prospectId)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception(SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            UpdateRecipientRequestType _request = new UpdateRecipientRequestType();
            _request.LIST_ID = listId;
            _request.OLD_EMAIL = email;

            ColumnElementType[] columnType = new ColumnElementType[2];

            columnType[0] = new ColumnElementType();
            columnType[0].NAME = "OPT_OUT";
            columnType[0].VALUE = "false";

            columnType[1] = new ColumnElementType();
            columnType[1].NAME = "ProspectId";
            columnType[1].VALUE = prospectId;

            //columnType[1] = new ColumnElementType();
            //columnType[1].NAME = "ProspectId";
            //columnType[1].VALUE = prospectId.ToString();

            _request.COLUMN = columnType;

            ListMgmtResponseType _response = client.UpdateRecipient(_request);

            if (_response.SUCCESS)
            {
                return SilverPOPMessages.OPT_IN_SUCCESSFULL;
            }
            else
            {
                throw new Exception(_response.Fault.FaultString);
            }
        }

        #endregion

        #region Get Job Status

        public static String GetJobStatus(SilverPopAccount silverPopAccount, long jobID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            GetJobStatusRequestType jobStatusType = new GetJobStatusRequestType();
            jobStatusType.JOB_ID = jobID;

            ReportingResponseType _response = client.GetJobStatus(jobStatusType);

            if (_response.SUCCESS)
            {
                return "Success:" + _response.JOB_STATUS;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }

        #endregion

        #region Calculate Query Total Contact Count In A Database/ContactList

        public static String CreateJOBForCalculateQuery(SilverPopAccount silverPopAccount, long queryID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            CalculateQueryRequestType calculateQueryRequest = new CalculateQueryRequestType();
            calculateQueryRequest.QUERY_ID=queryID;

            ListMgmtUserActionsResponseType _response = client.CalculateQuery(calculateQueryRequest);

            

            if (_response.SUCCESS)
            {
                return "Success:" + _response.JOB_ID;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }

        public static String GetJobStatusForCalculateQuery(SilverPopAccount silverPopAccount, long jobID)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            String queryName = String.Empty;
             String count = String.Empty;

            if (client == null)
                return SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND;


            GetJobStatusRequestType jobStatusType = new GetJobStatusRequestType();
            jobStatusType.JOB_ID = jobID;

            ReportingResponseType _response = client.GetJobStatus(jobStatusType);

            

            if (_response.SUCCESS)
            {
                if (_response.PARAMETERS != null && _response.PARAMETERS.Count() >= 2)
                {
                     count = _response.PARAMETERS[1].VALUE;
                }
                return "Success:" + _response.JOB_STATUS+" :"+count;
            }
            else
            {
                return _response.Fault.FaultString;
            }
        }



        #endregion

        #region Update Recipient

        public static List<UpdateResult> UpdateRecipientData(SilverPopAccount silverPopAccount, long databaseID, List<UpdatingSilverPOPContact> silverPOPUpdateContactList)
        {
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            List<UpdateResult> resultList = new List<UpdateResult>();

            String updatingColumnName = String.Empty;

            if (client == null)
            {
              resultList.Add(new UpdateResult("-111", SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND,""));
              return resultList;
            }

            UpdateRecipientRequestType updateRequest=new UpdateRecipientRequestType();
            updateRequest.LIST_ID= databaseID;

            foreach (UpdatingSilverPOPContact updatingContact in silverPOPUpdateContactList)
            {
                List<ColumnElementType> columnElementArray = new List<ColumnElementType>();
                ColumnElementType keyColumn = new ColumnElementType();

                keyColumn.NAME = updatingContact.KeyColumnName;
                keyColumn.VALUE = updatingContact.KeyColumnValue;

                columnElementArray.Add(keyColumn);

                foreach (UpdatingColumnNameValue updateColumn in updatingContact.UpdatingColumnNameValueList)
                {
                    ColumnElementType updateSilverPOPColumnNameValue = new ColumnElementType();
                    updateSilverPOPColumnNameValue.NAME = updateColumn.UpdatingColumnName;
                    updateSilverPOPColumnNameValue.VALUE = updateColumn.UpdatingColumnValue;

                    columnElementArray.Add(updateSilverPOPColumnNameValue);

                    updatingColumnName = updateColumn.UpdatingColumnName;
                    
                    
                }

                updateRequest.COLUMN = columnElementArray.ToArray();

                ListMgmtResponseType _response = client.UpdateRecipient(updateRequest);

                
                columnElementArray = null;

                resultList.Add(new UpdateResult(updatingContact.KeyColumnValue, _response.SUCCESS ? _response.SUCCESS.ToString() : _response.Fault.FaultString, updatingColumnName));
            }

            return resultList;
           
        }

        #endregion

        #region Get ReportID For Mailing

        public static List<SilverPOPReportIDInfo> GetReportIDForMailing(SilverPopAccount silverPopAccount, List<SilverPOPReportIDInfo> silverPOPReportIdInfoList, DateTime dateStart, DateTime dateEnd)
        {
          
            EngageSoapApiClientService client = LoginToSilverPopAccount(silverPopAccount.LoginEmail, silverPopAccount.LoginPassword);

            if (client == null)
                throw new Exception(SilverPOPMessages.SILVER_POP_ACCOUNT_NOT_FOUND);

            List<String> reportIdList = new List<String>();

            foreach (SilverPOPReportIDInfo report in silverPOPReportIdInfoList)
            {
                if (report.ReportId <= 0)
                {
                    GetReportIdByDateRequestType reportRequestType = new GetReportIdByDateRequestType();
                    reportRequestType.MAILING_ID = report.MailingId;
                    reportRequestType.DATE_START = String.Format("{0:MM/dd/yyyy hh:mm:ss}", dateStart);
                    reportRequestType.DATE_END = String.Format("{0:MM/dd/yyyy hh:mm:ss}", dateEnd);

                    ReportingResponseType _response = client.GetReportIdByDate(reportRequestType);

                    if (_response.SUCCESS)
                    {
                        report.ReportId = _response.Mailing[0] != null ? _response.Mailing[0].ReportId : 0;
                        report.JustGetFromSilverPOP = true;
                    }
                    else
                    {
                        throw new Exception(_response.Fault.FaultString);
                    }
                }
            }

            return silverPOPReportIdInfoList;
        }

        #endregion
    }//end class

}//end namespace
